//
//  CSSUserAccountViewModel.swift
//  weibo28
//
//  Created by chushushan on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CSSUserAccountViewModel: NSObject {

    
    var userAccount: CSSUserAcount?
    //单例
    static let shareUserAccount: CSSUserAccountViewModel = CSSUserAccountViewModel()
    
    override  init() {
        super.init()
        
        //获取归档对象
        userAccount = CSSUserAcount.loadUserAccount()
    }
    
    //只读属性
    var isLogin: Bool {
    
        return accessToken != nil
    }
    //判断accessToken是否过期
    var accessToken: String? {
    //判断有值
        guard let token = userAccount?.access_token else {
        return nil
        }
        //token是否过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        //降序
        if result == NSComparisonResult.OrderedDescending {
        
        return token
        } else {
        
        return nil
        }
        
    }
    
    
    //获取accesstoken
    func requestAccessToken(code: String, complete: (isSuccess: Bool) -> ()) {
    
    CSSNetWorkingTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
        if error != nil {
        
            print("网络请求异常")
            complete(isSuccess: false)
            return
        
        }
        
        guard let dic = response as? [String: AnyObject] else {
            print("数据不是一个正确的json格式")
            complete(isSuccess: false)
        return
        }
        
        let userAccount = CSSUserAcount(dic: dic)
        print(userAccount)
        
        self.requestUserInfo(userAccount, complete: complete)
        
        }
    
    }
    //获取用户信息
    func requestUserInfo(userAccount:CSSUserAcount, complete: (isSuccess: Bool) -> ()) {
    
    CSSNetWorkingTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
        
        if error != nil {
        
        print("网络请求异常")
            complete(isSuccess: false)
            return
        
        }
        
        guard let dic = response as? [String: AnyObject] else {
        
            print("不是一个正确的json数据")
            complete(isSuccess: false)
            return
        
        }
        
        userAccount.name = dic["name"] as? String
        userAccount.avatar_large = dic["avatar_large"] as? String
        
        self.userAccount = userAccount
//warning
        print(userAccount)
        
        //归档
        let result = userAccount.saveUserAccount()
        
        //
        if result {
        complete(isSuccess: true)
            
        } else {
        
        complete(isSuccess: false)
        }
        
        }
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
